<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>09 生成随机验证码</title>
</head>

<body>
    验证码： <input type="text" name="" id="tex">
    <input type="button" value="5689" id="rannum">
    <input type="button" value="确认" id="btn">
    <span id="inf"></span>
</body>
<script src="../common.js"></script>
<script>

    /* 
        编写生成4位数验证码的函数，并显示在页面，点击从新生成验证码

            需求：
                * 生成四位数的随机数显示到按钮里面
                * 点击按钮可以切换一个新的随机数
                * 点击确认按钮，获取表单的值和随机数比较，相同才是验证通过，允许提交

    */

    function ranNum() {
        // 生成4位数的随机数并返回
        var html = '';
        for (var i = 0; i < 4; i++) {
            var num = parseInt(Math.random() * 10);
            html += num;
        }
        return html;
    }

    var tex = getid('tex');
    var rannum = getid('rannum');
    var btn = getid('btn');
    var inf = getid('inf');

    function setData() {
        var num = ranNum(); // 返回的随机数
        rannum.value = num;
    }

    setData();

    rannum.onclick = function () {
        setData();
    }

    // 点击确认时判断验证码是否通过
    btn.onclick = function() {
        var texVal = tex.value;
        var ranVal = rannum.value;

        if (texVal == ranVal) {
            // 验证通过
            inf.innerHTML = '验证码正确';
            inf.style.color = 'green';
        } else {
            // 验证未通过
            inf.innerHTML = '验证码错误';
            inf.style.color = 'pink';
        }
    }

</script>

</html>